package com.yfux.cling_player.service.controller;

import android.content.Context;
import android.media.AudioManager;


import com.yfux.cling_player.util.LogUtil;

import org.fourthline.cling.model.types.UnsignedIntegerTwoBytes;

public class AudioRenderController extends AudioControl {

    private final UnsignedIntegerTwoBytes muteVolume = new UnsignedIntegerTwoBytes(0);
    private final AudioManager audioManager;
    private UnsignedIntegerTwoBytes currentVolume;
    LogUtil logger = new LogUtil("AudioRenderController");

    public AudioRenderController(Context context) {
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int maxMusicVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        currentVolume = new UnsignedIntegerTwoBytes(volume * 100L / maxMusicVolume);
    }

    @Override
    public void setMute(String channelName, boolean desiredMute) {
        setMute(channelName, desiredMute);
        setVolume(channelName, desiredMute ? muteVolume : currentVolume);
    }

    @Override
    public boolean getMute(String channelName) {
        return getVolume(channelName).getValue() == 0L;
    }

    @Override
    public void setVolume(String channelName, UnsignedIntegerTwoBytes desiredVolume) {
        super.setVolume(channelName, desiredVolume);
        currentVolume = desiredVolume;
        int volume = desiredVolume.getValue().intValue();
        int adjustVolume = volume * audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) / 100;
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, adjustVolume, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
    }

    @Override
    public UnsignedIntegerTwoBytes getVolume(String channelName) {
        return new UnsignedIntegerTwoBytes(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100L / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
    }
}